import datetime
import time

from django.http import JsonResponse
import json
# Create your views here.
from django.views import View

# Create your views here.
from home.models import House
from ihome.utils.mixins import LoginRequiredMixin
from order.models import Order
from users.models import User


class OrderAddView(LoginRequiredMixin,View):
    def post(self, request):
        # 接收参数
        req_data = json.loads(request.body)
        house_id = req_data.get('house_id')
        start_date = req_data.get('start_date')
        end_date = req_data.get('end_date')
        # 检验参数
        if not all([house_id, start_date, end_date]):
            return JsonResponse({
                'errno': 400,
                'errmsg': '缺省必要参数！'
            })
        if start_date > end_date:
            return ({
                'errno': 400,
                'errmsg': '参数错误！'
            })

        try:
            house = House.objects.get(id=house_id)
        except Exception as e:
            return JsonResponse({
                'errno': 400,
                'errmsg': '数据库操作错误！'
            })
        # 判断下单的用户身份
        try:
            user = House.objects.get(id=house_id).user
        except Exception as e:
            return JsonResponse({
                'errno': 400,
                'errmsg': '数据库操作错误'
            })
        # 查询当前用户的的多个订单
        orders = Order.objects.filter(house_id=house_id,
                                      status__in=[Order.ORDER_STATUS['WAIT_ACCEPT'],
                                                  Order.ORDER_STATUS['WAIT_PAYMENT'],
                                                  Order.ORDER_STATUS['PAID'],
                                                  Order.ORDER_STATUS['WAIT_COMMENT'],
                                                  Order.ORDER_STATUS['COMPLETE']]
                                      )
        if request.user == user:
            return JsonResponse({
                'errno': 400,
                'errmsg': '房东不能给自己下单'
            })
        st = datetime.datetime.date(datetime.datetime.strptime(start_date, '%Y-%m-%d'))
        et = datetime.datetime.date(datetime.datetime.strptime(end_date, '%Y-%m-%d'))
        day = (et - st).days
        if house.max_days != 0:
            if house.max_days < day or house.min_days > day:
                return JsonResponse({
                    'errno': 400,
                    'errmsg': '入住时间有误！'
                })
        else:

            if house.min_days > day:
                return JsonResponse({
                    'errno': 400,
                    'errmsg': '入住时间有误！'
                })
        for order in orders:
            start_date1 = order.begin_date
            end_date1 = order.end_date
            # 判断房子在日期内有没有被人预定
            start_date1 = str(start_date1)
            end_date1 = str(end_date1)
            sd = time.mktime(time.strptime(start_date, '%Y-%m-%d'))
            ed = time.mktime(time.strptime(end_date, '%Y-%m-%d'))
            sd1 = time.mktime(time.strptime(start_date1, '%Y-%m-%d'))
            ed1 = time.mktime(time.strptime(end_date1, '%Y-%m-%d'))
            # 如果开始时间或结束时间在某一个订单的日期范围内，则房子被预定了
            if sd1 <= sd <= ed1 or sd1 <= ed <= ed1 or sd < sd1 < ed or sd < ed1 < ed:
                return JsonResponse({
                    'errno': 400,
                    'errmsg': '房子已经被订了!'})
        # 新增订单
        order = Order.objects.create(
            user=request.user,
            house_id=house_id,
            begin_date=st,
            end_date=et,
            days=day,
            house_price=house.price,
            amount=int(house.price) * int(day),
            status=Order.ORDER_STATUS['WAIT_ACCEPT'],

        )
        return JsonResponse({"errno": 0,
                             'errmsg': '下单成功',
                             'data': {
                                 "order_id": order.id
                             }})

    def get(self, request):
        role = request.GET.get('role')
        user = request.user
        if role == 'custom':
            # 登录的是客户
            # 查询用户订单
            order_list = Order.objects.filter(user=user)
            orders = []

            for order in order_list:
                orders.append({
                    "amount": order.amount,
                    "comment": order.comment,
                    "ctime": order.create_time.strftime("%Y-%m-%d"),
                    "days": order.days,
                    "end_date": order.end_date,
                    "img_url": 'http://192.168.19.131:8888/' + order.house.index_image_url,
                    "order_id": order.id,
                    "start_date": order.begin_date,
                    "status": Order.ORDER_STATUS_ENUM[order.status],
                    "title": order.house.title
                })
        else:
            # 登录的是房东
            # 查询房东订单
            order_list = Order.objects.filter(house__user=user)
            orders = []
            for order in order_list:
                orders.append({
                    "amount": order.amount,
                    "comment": order.comment,
                    "ctime": order.create_time.strftime("%Y-%m-%d"),
                    "days": order.days,
                    "end_date": order.end_date,
                    "img_url": 'http://192.168.19.131:8888/' + order.house.index_image_url,
                    "order_id": order.id,
                    "start_date": order.begin_date,
                    "status": Order.ORDER_STATUS_ENUM[order.status],
                    "title": order.house.title
                })
        return JsonResponse({
            "errmsg": "OK",
            "errno": "0",
            'data': {'orders': orders}
        })



class OrdersStatusView(LoginRequiredMixin, View):

    def put(self, request, order_id):
        req_data = json.loads(request.body)
        action = req_data.get("action")
        reason = req_data.get('reason')

        if action == 'accept':#接单
            order = Order.objects.get(id=order_id)
            order.status = Order.ORDER_STATUS['WAIT_COMMENT']
            order.house.order_count += 1
            order.house.save()
            order.save()
            orders = Order.objects.filter(house_id=order.house_id,
                                          status__in=[Order.ORDER_STATUS['WAIT_ACCEPT']]
                                          )
            for order1 in orders:
                start_date1 = order1.begin_date
                end_date1 = order1.end_date
                # 判断房子在日期内有没有被人预定
                start_date1 = str(start_date1)
                end_date1 = str(end_date1)
                sd = time.mktime(time.strptime(str(order.begin_date), '%Y-%m-%d'))
                ed = time.mktime(time.strptime(str(order.end_date), '%Y-%m-%d'))
                sd1 = time.mktime(time.strptime(start_date1, '%Y-%m-%d'))
                ed1 = time.mktime(time.strptime(end_date1, '%Y-%m-%d'))
                # 如果开始时间或结束时间在某一个订单的日期范围内，则房子被预定了
                if sd1 <= sd <= ed1 or sd1 <= ed <= ed1 or sd < sd1 < ed or sd < ed1 < ed:
                    order1.status = Order.ORDER_STATUS['REJECTED']
                    order1.comment = '已接受其他订单'  # 拒单原因
                    order1.save()
            return JsonResponse({
                "errno": 0,
                'errmsg': '房东已接单'
            })
        else:  # 拒单
            if not reason:
                return JsonResponse({
                    "errno": 400,
                    'errmsg': '缺少必传参数'
                })
            order = Order.objects.get(id=order_id)
            order.status = Order.ORDER_STATUS['REJECTED']
            order.comment = reason  # 拒单原因
            order.save()
            return JsonResponse({
                "errno": 0,
                'errmsg': '拒单成功'
            })


class OrderCommentView(LoginRequiredMixin, View):

    def put(self, request, order_id):

        # 订单的评论信息或者拒单原因

        comment = json.loads(request.body).get('comment')

        if request.user == 'custom':  # 房客状态（待评价）
            order = Order.objects.get(id=order_id)
            order.status = Order.ORDER_STATUS['WAIT_COMMENT']
            order.comment = comment
            order.save()
            return JsonResponse({
                "errno": 0,
                'errmsg': '发表评价成功'
            })
        else:
            # 房东状态（已接单）
            order = Order.objects.get(id=order_id)
            if order.status == Order.ORDER_STATUS['WAIT_COMMENT']:
                order.comment = comment
                order.status = Order.ORDER_STATUS['COMPLETE']
                order.save()
                return JsonResponse({
                    "errno": 0,
                    'errmsg': '已接单'
                })
            else:
                # 房东拒单，填写拒单原因
                order.comment = comment
                order.status = Order.ORDER_STATUS['REJECTED']
                order.save()
                return JsonResponse({
                    "errno": 0,
                    'errmsg': '拒单成功'
                })
